import time
from datetime import datetime, timedelta

from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import db
from info.constants import ADMIN_USER_PAGE_MAX_COUNT, ADMIN_NEWS_PAGE_MAX_COUNT, QINIU_DOMIN_PREFIX
from info.models import User, News, Category
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import admin_blu


# 新闻分类管理
@admin_blu.route('/admin/news_type', methods=['get', 'post'])
def news_type():
    if request.method == 'GET':
        categorys = Category.query.all()
        category_list = []
        for category in categorys:
            category_dic = category.to_dict()
            category_list.append(category_dic)
        category_list.pop(0)
        # 查询这条新闻的所有信息

        data = {
            'category_list': category_list
        }

        return render_template('admin/news_type.html',data=data)


    name = request.json.get('name')
    id = request.json.get('id')
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if id:
        try:
            id = int(id)
            category = Category.query.get(id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

        category.name = name
        return jsonify(errno=RET.OK, errmsg='添加成功')

    category = Category()
    category.name = name

    try:
        db.session.add(category)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='添加失败')

    return jsonify(errno=RET.OK, errmsg='添加成功')




# 新闻审核的详细页面以及操作
@admin_blu.route('/admin/news_edit_detail', methods=['GET', 'POST'])
def news_edit_detail():
    if request.method == 'GET':
        news_id = request.args.get('news_id')
        news = News.query.get(news_id)
        # 查询处所有的新闻分类
        categorys = Category.query.all()
        category_list = []
        for category in categorys:
            category_dic = category.to_dict()
            category_dic['is_selected'] = False
            if category.id == news.category_id:
                category_dic['is_selected'] = True
            category_list.append(category_dic)
        category_list.pop(0)
        # 查询这条新闻的所有信息

        data = {
            'category_list': category_list,
            'news': news.to_dict()
        }
        return render_template('admin/news_edit_detail.html', data=data)

    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    if not all([news_id, title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='新闻查询失败')

    if index_image:
        try:
            file = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg='数据错误')
        # 上传新闻图片
        try:
            key = storage(file)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg='图片上传错误')
        news.index_image_url = QINIU_DOMIN_PREFIX + key

    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    return jsonify(errno=RET.OK, errmsg='操作成功')


# 新闻编辑页面的渲染
@admin_blu.route('/admin/news_edit')
def news_edit():
    keywords = request.args.get('keywords', None)
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
    total_page = 1
    current_page = 1
    news = None

    filters = []
    filters.append(News.status == 0)
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).paginate(page, ADMIN_NEWS_PAGE_MAX_COUNT)
        total_page = paginate.pages
        current_page = paginate.page
        news = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_list = []
    for new in news:
        news_list.append(new.to_basic_dict())

    data = {
        'news_list': news_list,
        'total_page': total_page,
        'current_page': current_page
    }

    return render_template('admin/news_edit.html', data=data)


# 新闻审核的详细页面以及操作
@admin_blu.route('/admin/news_review_detail', methods=['GET', 'POST'])
def news_review_detail():
    if request.method == 'GET':
        news_id = request.args.get('news_id')
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        data = {
            'news': news.to_dict()
        }
        return render_template('admin/news_review_detail.html', data=data)
    # 审核逻辑
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if action not in ['accept', 'reject']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='数据查询错误')

    if action == 'accept':
        news.status = 0
    else:
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg='请输入拒绝原因')
        news.status = -1
        news.reason = reason

    return jsonify(errno=RET.OK, errmsg='操作成功')




    # 新闻审核


# 审核页面的展示
@admin_blu.route('/admin/news_review')
def news_review():
    keywords = request.args.get('keywords', None)
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
    total_page = 1
    current_page = 1
    news = None

    filters = []
    filters.append(News.status != 0)
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).paginate(page, ADMIN_NEWS_PAGE_MAX_COUNT)
        total_page = paginate.pages
        current_page = paginate.page
        news = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_list = []
    for new in news:
        news_list.append(new.to_review_dict())

    data = {
        'news_list': news_list,
        'total_page': total_page,
        'current_page': current_page
    }
    return render_template('admin/news_review.html', data=data)


# 用户列表
@admin_blu.route('/admin/user_list')
def user_list():
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
    total_page = 1
    current_page = 1
    users = None
    try:
        paginate = User.query.filter(User.is_admin == False).paginate(page, ADMIN_USER_PAGE_MAX_COUNT)
        total_page = paginate.pages
        current_page = paginate.page
        users = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    user_list = []
    for user in users:
        user_list.append(user.to_admin_dict())

    data = {
        'user_list': user_list,
        'total_page': total_page,
        'current_page': current_page
    }

    return render_template('admin/user_list.html', data=data)


# 用户数量查询
@admin_blu.route('/admin/user_count')
def user_count():
    # 总用户数量
    total_user = 0
    try:
        total_user = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 月新增用户数量
    mon_count = 0
    t = time.localtime()
    mon_time = datetime.strptime(('%d-%02d-01' % (t.tm_year, t.tm_mon)), '%Y-%m-%d')
    try:
        mon_count = User.query.filter(User.create_time > mon_time, User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 日新增数量
    day_count = 0
    t = time.localtime()
    day_time = datetime.strptime(('%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)), '%Y-%m-%d')
    try:
        day_count = User.query.filter(User.create_time > mon_time, User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询表单信息
    # 1.当天的事件并转换成字符串
    now_time = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    # 2.定义两个空列表，一个出存时间，一个储存当天的活跃人数
    time_dic = []
    count_dic = []
    # 3.循环 获得一个月的时间和每天的活跃人数
    for i in range(0, 31):
        T1 = now_time - timedelta(days=i)  # 当天时间减去天数获取这个一个月的时间
        time_dic.append(T1.strftime('%Y-%m-%d'))
        T2 = T1 + timedelta(days=1)  # 获取每天的前一天的时间
        now_day_count = None
        try:
            now_day_count = User.query.filter(User.last_login >= T1, User.last_login < T2,
                                              User.is_admin == False).count()
        except Exception as e:
            current_app.logger.error(e)
        count_dic.append(now_day_count)

    time_dic.reverse()
    count_dic.reverse()

    data = {
        'total_user': total_user,
        'mon_count': mon_count,
        'day_count': day_count,
        'time_dic': time_dic,
        'count_dic': count_dic
    }

    return render_template('admin/user_count.html', data=data)


# 管理主页
@admin_blu.route('/admin/index')
def admin_index():
    user = g.user
    data = {
        'user': user.to_dict()
    }

    return render_template('admin/index.html', data=data)


# 管理登陆
@admin_blu.route('/admin/login', methods=['get', 'post'])
def admin_login():
    if request.method == 'GET':
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        if user_id and is_admin:
            return redirect('/admin/index')

        return render_template('admin/login.html')

    username = request.form.get('username')
    password = request.form.get('password')

    # 判断参数
    if not all([username, password]):
        return render_template('admin/login.html', errmsg='参数错误')

    user = User.query.filter(User.nick_name == username, User.is_admin == True).first()
    if not user:
        return render_template('admin/login.html', errmsg='用户不存在')
    if not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg='密码错误')

    # 保存管理员登陆状态
    session['user_id'] = user.id
    session['user_mobile'] = user.mobile
    session['user_nick_name'] = user.nick_name
    session['is_admin'] = user.is_admin

    return redirect('/admin/index')
